package com.not_found404.bilibilimerge;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;

/**
 * Created by chengww on 2017/9/3.
 */

public class FileUtils {
    public static boolean copy(String path, String copyPath) throws IOException {
        File filePath = new File(path);
        DataInputStream read;
        DataOutputStream write;
        if (filePath.isDirectory()) {
            File[] list = filePath.listFiles();
            for (File aList : list) {
                String newPath = path + File.separator + aList.getName();
                String newCopyPath = copyPath + File.separator + aList.getName();
                File newFile = new File(copyPath);
                if (!newFile.exists()) {
                    newFile.mkdir();
                }
                copy(newPath, newCopyPath);
            }
            return true;
        } else if (filePath.isFile()) {
            FileInputStream fi = null;
            FileOutputStream fo = null;
            FileChannel in = null;
            FileChannel out = null;

            fi = new FileInputStream(path);
            fo = new FileOutputStream(copyPath);
            in = fi.getChannel();//得到对应的文件通道
            out = fo.getChannel();//得到对应的文件通道
            in.transferTo(0, in.size(), out);//连接两个通道，并且从in通道读取，然后写入out通道

            fi.close();
            in.close();
            fo.close();
            out.close();
            return true;
        } else {
            return false;
        }
    }

    public static boolean isPkgInstalled(Context context, String pkgName) {
        PackageInfo packageInfo = null;
        try {
            packageInfo = context.getPackageManager().getPackageInfo(pkgName, 0);
        } catch (PackageManager.NameNotFoundException e) {
            packageInfo = null;
            e.printStackTrace();
        }
        return packageInfo != null;
    }

    public static boolean deleteFolder(File file) {
        if (!file.exists()) {
            return false;
        }
        if (file.isFile()) {
            file.delete();
            return true;
        } else {
            File[] files = file.listFiles();
            for (File file1 : files) {
                //System.out.println(root);
                deleteFolder(file1);
            }
            file.delete();
            return true;
        }
    }
}

